package cn.com.dhcc.app.pub.core.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.log4j.Logger;

import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;

public class HttpUtil {
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getDetachLogger(LOGTYPE.FTP);

	public static boolean checkUrl(String url)  {
		boolean flag = false;
		HttpURLConnection httpURLConnection = null;
		OutputStream out = null; // 写
		InputStream in = null; // 读
		int responseCode = 0; // 远程主机响应的HTTP状态码
		URL sendUrl;
		try {
			sendUrl = new URL(url);
			httpURLConnection = (HttpURLConnection) sendUrl.openConnection();
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setDoOutput(true); // 指示应用程序要将数据写入URL连接,其值默认为false
			httpURLConnection.setUseCaches(false);
			httpURLConnection.setConnectTimeout(30000); // 30秒连接超时
			httpURLConnection.setReadTimeout(30000); // 30秒读取超时
			out = httpURLConnection.getOutputStream();
			out.write("".getBytes());
			out.flush(); // 清空缓冲区,发送数据
			responseCode = httpURLConnection.getResponseCode();
			logger.info("HttpUtil.checkUrl().验证url " + url + " 。状态码：" + responseCode);
			if(responseCode == 200){
				flag = true;
			}else{
				logger.error("HttpUtil.checkUrl().验证url " + url + " 失败。状态码：" + responseCode);
			}
		} catch (IOException e) {
			 logger.info("HttpUtil.checkUrl().验证url " + url + " 失败。发生IOException：" + e);
		}finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
		if (httpURLConnection != null) {
			httpURLConnection.disconnect();
			httpURLConnection = null;
		}
	}
		
		return flag;
	}
	public static void main(String[] args) {
	  System.out.println(HttpUtil.checkUrl("http://localhost:8084/turbo"));
	}
}
